package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.YearLimitDimension
import grails.gorm.transactions.Transactional
import grails.converters.JSON
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class MortgageController
{

    def apiService
    def springSecurityService
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def loansDuration = params["loansDuration"]
        def mortgageStatus = params["mortgageStatus"]
        def loansAmountStart = params["loansAmountStart"]
        def loansAmountEnd = params["loansAmountEnd"]
        def loansBalanceStart = params["loansBalanceStart"]
        def loansBalanceEnd = params["loansBalanceEnd"]
        def isNonPerformingLoan = params["isNonPerformingLoan"]
        def startDateStart = params["startDateStart"]
        def startDateEnd = params["startDateEnd"]
        def accountId = params["accountId"]
        def mortgageType = params["mortgageType"]
        def mortgagePattern = params["mortgagePattern"]
        def mortgageCategory = params["mortgageCategory"]
        def riskWarningLevel = params["riskWarningLevel"]
        def serialNumber = params["serialNumber"]

        def user = User.findById(springSecurityService.principal.id)
        def mortgageQueryParam = new HashMap()
        def mortgageSql = " from Mortgage e where e.account.id in " + Account.FilterAccountSql(user)

        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.account.city.zoneNumber = :city "
            mortgageQueryParam["city"] = city
        }
        if (loansDuration && loansDuration != "")
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    sql += " and e.loansDuration > :loansDurationMin and e.loansDuration<= :loansDurationMax "
                    mortgageQueryParam['loansDurationMin'] = loansDurationMin
                    mortgageQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and e.mortgageStatus.id = :mortgageStatus "
            mortgageQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            sql += "and e.loansAmount >= :loansAmountStart "
            mortgageQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            sql += "and e.loansAmount <= :loansAmountEnd "
            mortgageQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            sql += "and e.loansBalance >= :loansBalanceStart "
            mortgageQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            sql += "and e.loansBalance <= :loansBalanceEnd "
            mortgageQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (isNonPerformingLoan && isNonPerformingLoan != "")
        {
            sql += " and e.isNonPerformingLoan = :isNonPerformingLoan "
            mortgageQueryParam['isNonPerformingLoan'] = Boolean.parseBoolean(isNonPerformingLoan)
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            sql += "and e.startDate >=  :dateStart "
            mortgageQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            sql += "and e.startDate <=  :dateEnd "
            mortgageQueryParam['dateEnd'] = dateEnd
        }
        if (accountId && accountId != "")
        {
            sql += " and e.account.id = :accountId "
            mortgageQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (mortgagePattern && mortgagePattern != "")
        {
            sql += " and e.mortgagePattern.id = :mortgagePattern "
            mortgageQueryParam['mortgagePattern'] = Long.parseLong(mortgagePattern)
        }
        if (mortgageType && mortgageType != "")
        {
            sql += " and e.mortgageType.id = :mortgageType "
            mortgageQueryParam['mortgageType'] = Long.parseLong(mortgageType)
        }
        if (mortgageCategory && mortgageCategory != "")
        {
            sql += " and e.mortgageCategory.id = :mortgageCategory "
            mortgageQueryParam['mortgageCategory'] = Long.parseLong(mortgageCategory)
        }
        if (riskWarningLevel && riskWarningLevel != "")
        {
            sql += " and e.riskWarningLevel.id = :riskWarningLevel "
            mortgageQueryParam['riskWarningLevel'] = Long.parseLong(riskWarningLevel)
        }
        if (serialNumber && serialNumber != "") 
        {
            sql += " and e.serialNumber = '${serialNumber}' "
        }
        def countSql = " select count(e.id) from Mortgage e where e.account.id in " + Account.FilterAccountSql(user)

        countSql += sql
        sql += "order by e.serialNumber desc "
        mortgageSql += sql

        def mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: max, offset: offset])
        def mortgageCount = Mortgage.executeQuery(countSql, mortgageQueryParam)

        def accountManageAccountSql = " from Account o where o.id in  " + Account.FilterAccountSql(user)
        def accountManageAccountList = Account.executeQuery(accountManageAccountSql)

        respond mortgageList, model: [mortgageCount: mortgageCount[0], params: params, accountManageAccountList: accountManageAccountList], view: 'index'
    }

    def show(Mortgage mortgage)
    {
        def repaymentImportList = RepaymentImport.findAllByMortgageAndExecStatus(mortgage,ExecStatusDict.SUCCESS(), [max: params.max, offset: params.offset, sort: 'id', order: 'desc'])
        respond mortgage, model: [repaymentImportList: repaymentImportList, repaymentImportCount: RepaymentImport.countByMortgageAndExecStatus(mortgage,ExecStatusDict.SUCCESS())]
    }

    def create()
    {
        respond new Mortgage(params)
    }

    @Transactional
    def save(Mortgage mortgage)
    {
        def collateralId = params['collateralId']
        def collateral = Collateral.findById(Long.parseLong(collateralId))

        if(mortgage == null || collateral == null ){
            println "not found"
            return
        }

        if (mortgage.hasErrors()) {
            println mortgage.errors
            transactionStatus.setRollbackOnly()
            respond mortgage.errors, view:'create'
            return
        }

        mortgage.save flush:true

        def mortgageCollateral = new MortgageCollateral()
        mortgageCollateral.collateral = collateral
        mortgageCollateral.mortgage = mortgage
        mortgageCollateral.save flush:true

        redirect action:"estateShow" ,controller:"estate",params:[id:collateral?.id]


    }

    def edit(Mortgage mortgage)
    {
        respond mortgage
    }

    @Transactional
    def updateMortgage(Mortgage mortgage){
        def collateralId = params['collateralId']

        //如果押品id无效 不处理
        def collateral = Collateral.findById(Long.parseLong(collateralId))
        if(collateral == null){
            return
        }

        if (mortgage.hasErrors()) {
            println mortgage.errors
            transactionStatus.setRollbackOnly()
            respond mortgage.errors, view:'create'
            return
        }

        mortgage.save flush:true

        redirect action:"estateShow" ,controller:"estate",params:[id:collateral?.id]
    }

    @Transactional
    def update(Mortgage mortgage)
    {
        if (mortgage == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (mortgage.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond mortgage.errors, view: 'edit'
            return
        }

        mortgage.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'mortgage.label', default: 'Mortgage'), mortgage.id])
                redirect mortgage
            }
            '*' { respond mortgage, [status: OK] }
        }
    }

    @Transactional
    def delete(Mortgage mortgage) {
        def collateralId = params['collateralId']
        def collateral = Collateral.findById(Long.parseLong(collateralId))
        def mortgageCollateral = MortgageCollateral.findByMortgageAndCollateral(mortgage,collateral)
        if(!mortgageCollateral){
            println "not find"
            return
        }
        mortgageCollateral.delete flush:true
        //contract.delete flush:true

        redirect action:"estateShow" ,controller:"estate",params:[id:collateral?.id]
    }


    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'mortgage.label', default: 'Mortgage'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
